<?php
/**
 * Created by IntelliJ IDEA.
 * User: ahwwl
 * Date: 18-7-18
 * Time: 下午4:59
 */

namespace commen;



use think\Log;
use think\Request;

class axsms
{
    private static $appkey="TTXT_9009";
    private static $secret = "yzmcs_ttxt_209";
    private static $url = "http://47.98.65.120:9110";


    static function get_sms_notify()
    {
        $info = ["error" => 1, "error_info" => "", "data" => [], "request_data"=>""];
        $request = Request::instance();
        $content = $request->getContent();
        $header = $request->header();
        $info["request_data"] = ["header"=>$header,"body"=>$content];
        $ts = $request->header("ts","");
        $appkey =  $request->header("appkey","");
        $msgdgt = $request->header("msgdgt","");
        try{
            if($appkey != self::$appkey)
                exception("appkey不一致");

            if(!empty($content) && false !== strpos( $request->contentType(), 'application/json'))
            {
                $content = json_decode($content,true);
            }else{
                $content = [];
            }
            $body = $content;
            $body["appkey"] = self::$appkey;
            $body["ts"] = $ts;
            $m = self::make_msgdgt($body);
            if(strtoupper($msgdgt) != strtoupper($m))
                exception("验证失败");
            foreach ($content as $key=>$val)
            {
                if(!in_array($key,["requestId","telA","telB","telX","subid","calltype","calltime","callid","smscontent"]))
                {
                    unset($content[$key]);
                }
            }
            if(!empty($content["smscontent"]))
            {
                $smscontent = self::decode($content["smscontent"]);
                if($smscontent)
                    $content["smscontent"] = $smscontent;
            }
            $content["request_data"] = json_encode($info["request_data"]);
            $info["error"] = 0;
            $info["data"] = $content;
        }catch (\Exception $e)
        {
            $info["error_info"] = $e->getMessage();
        }


        return $info;

    }
    static function bind($telA,$telX,$areacode,$name,$cardno)
    {
        $body = [
            "requestId"=>md5(NOW_TIME),
            "telA" => $telA,
            "telX" => $telX,
            "areacode"=>$areacode,
            "subts" => date("YmdHis",NOW_TIME),
            "name" => $name,
            "cardtype" => 0,
            "cardno" => $cardno,
            "expiration" => 0,
            "extra" =>["smsmtchannel"=>2]

        ];
        return self::get_curl("POST","/v2/ax/mode101", $body);
    }
    static function unbind($subid)
    {
        return self::get_curl("DELETE","/v2/ax/".$subid, []);
    }
    static function query_bind($subid)
    {
        return self::get_curl("GET","/v2/ax/subid/".$subid, []);
    }
    static function sms($subid,$telB,$smscontent)
    {

        $body = ["requestId"=>md5(NOW_TIME),"telB" => $telB,"smscontent" => self::encode($smscontent)];
        return self::get_curl("PUT","/v2/ax/onlinesms/".$subid, $body);
    }
    static function make_msgdgt($body)
    {

        ksort($body);
        $value = "";
        foreach ($body as $key=>$val)
        {
            if($key == "extra")
            {
                $val = json_encode($val);
            }
            $value .= $key.$val;
        }
        return md5(self::$secret.$value);
    }
    static function get_curl($method,$action, $body)
    {
        $ts = date("YmdHis",NOW_TIME).rand(100,999);
        $headers = ["appkey: ".self::$appkey,
            "ts: ".$ts,
            "Accept: application/json;charset=utf-8",
            "Content-Type: application/json;charset=utf-8"];
        $url = self::$url . $action;
        if(is_array($body))
        {
            $body["appkey"] = self::$appkey;
            $body["ts"] = $ts;
            $body["msgdgt"] = self::make_msgdgt($body);
            $body = json_encode($body);
        }
        $info = ["error" => 1, "error_info" => "", "data" => [],"response_data"=>"","request_data"=>""];

        $info["request_data"] = json_encode(["method"=>$method,"url"=>$url,"headers"=>$headers,"body"=>$body]);
        $result= self::curl_url($method,$url, $headers, $body);
        $info["response_data"] = json_encode($result);
        if ($result["code"] == 200) {
            $body = json_decode($result["body"], true);
            if(empty($body))
                $info["error_info"] = $result["error_info"];
            else{
                if($body["code"]==0)
                {
                    $info["error"] = 0;
                    $info["data"] = $body["data"];
                }else{
                    $info["error_info"] = $body["message"];
                }
            }

        } else {
            $info["error_info"] = $result["error_info"];
        }
        Log::INFO(json_encode($info));
        return $info;
    }

    static function curl_url($method,$url, $headers=[], $body)
    {
        $result = ["code" => 1, "body" => "", "error_info" => ""];
        try {
            $ch = curl_init();
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            if (!empty($headers))
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            switch($method) {
                case 'GET':
                    break;
                case 'POST':
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $body); //设置请求体，提交数据包
                    break;
                case 'PUT':
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $body); //设置请求体，提交数据包
                    break;
                case 'DELETE':
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
                    break;
            }

            //执行并获取HTML文档内容
            $output = curl_exec($ch);
//            print_r($output);
            if ($output === false) {
                $result["error_info"] = curl_errno($ch);
            }
            $result["code"] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $result["body"] = $output;
            //释放curl句柄
            curl_close($ch);
        } catch (\Exception $e) {
            $result["error_info"] = $e->getMessage();
        }
        return $result;
    }
    static function encode($str)
    {
        $buffer = [];
        $length = strlen($str);
        for($pos=0;$pos<$length;)
        {
            if(ord(substr($str,$pos,1))>=161)
            {
                $tmpChar=substr($str,$pos,3);
                $pos += 3;
            }else{
                $tmpChar=substr($str,$pos,1);
                $pos++;
            }
            $buffer[] = bin2hex($tmpChar);
        }
        return strtoupper(join("",$buffer));
    }
    static function decode($str)
    {
        $buffer = [];
        $length = strlen($str);
        for ($pos=0;$pos<$length;)
        {
            $ss = pack("H2",substr($str,$pos,2));
            if(ord($ss)>=161)
            {
                $tmpChar = pack("H6",substr($str,$pos,6));
                $pos += 6;
            }else{
                $tmpChar = $ss;
                $pos += 2;
            }
            $buffer[] = $tmpChar;
        }
        return join("",$buffer);
    }
}